/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Main;

import java.io.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author anhdung
 */
public class Transfer {
    Packet pk; 
    BroadCast bc;
    byte[] Buf;
    
    public Transfer() {
        pk =new Packet(0, true, 0, null);
        bc = new BroadCast();
        Buf = new byte[1024];
    }
    
    public void Download(DatagramSocket socket, DatagramPacket Packet)
    {
        try {
            Packet = new DatagramPacket(Buf, Buf.length);
            socket.receive(Packet);
            //path to save file
            String dirPath = System.getProperty("user.dir");

            //getting file name
            socket.receive(Packet);
            String filedata = new String(Packet.getData());
            filedata = filedata.substring(0, filedata.lastIndexOf("\n"));
            dirPath = dirPath + "\\" + filedata;

            //getting data
            socket.receive(Packet);
            filedata = new String(Packet.getData());
            filedata = filedata.substring(0, filedata.lastIndexOf("\n"));
            
            if(Integer.valueOf(filedata.substring(0,1))== pk.Get_Ack()) {
                pk.Set_Check((pk.Get_Check()==false)?true:false);
                //saving content of file
                FileOutputStream fout = new FileOutputStream(dirPath);
                fout.write(filedata.getBytes());
            }
            
        } catch (IOException ex) {
            Logger.getLogger(Transfer.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

class Packet implements Serializable {
    int flag;
    boolean check;
    int ack;
    byte[] data;
    
    public Packet(int flag,boolean check,int ack, byte[] data) {
        this.flag = flag;
        this.check = check;
        this.ack = ack;
        this.data = data;
    }
    
    public int Get_Flag() {
        return flag;
    }
    public boolean Get_Check() {
        return check;
    }
    public int Get_Ack() {
        return ack;
    }
    public byte[] Get_Data() {
        return data;
    }
    public void Set_Flag(int Flag) {
        this.flag = Flag;
    }
    public void Set_Check(boolean check) {
        this.check = check;
    }
    public void Set_Ack(int ack) {
        this.ack = ack;
    }
    public void Set_Data(byte[] data) {
        this.data = data;
    }
}
